import * as React from "react";
import AutosizeInput from "react-input-autosize";
import "./index.scss";
import formcontext from "../form";

class Calculate extends React.Component {
  state = {
    data: 0,
  };

  static getDerivedStateFromProps(props) {
    const { form, type, start: startkey, end: endkey } = props;
    let start;
    let end;
    switch (type) {
      case "number":
        start = form.getFieldValue(startkey) || 0;
        end = form.getFieldValue(endkey) || 0;
        return {
          data: end - start,
        };
      case "date":
        start = form.getFieldValue(startkey) || new Date();
        end = form.getFieldValue(endkey) || new Date();
        return {
          data: Math.round((end - start) / (24 * 3600 * 1000)),
        };
      default:
        return {
          data: 0,
        };
    }
  }

  render() {
    const { data } = this.state;
    const { placeholder, label } = this.props;
    return (
      <div className="formitem">
        <label>{label || "用户名"}</label>
        <AutosizeInput
          style={{ minWidth: "5vw" }}
          value={data}
          disabled
          placeholder={placeholder}
        />
      </div>
    );
  }
}

export default props => {
  const { node } = props;
  const form = React.useContext(formcontext);
  return (
    <Calculate {...node.data} form={form} />
  );
};
